package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.code.LogType;
import com.pactera.jep.core.code.OperateType;
import com.pactera.jep.core.spring.AutoLog;
import com.pactera.jep.entity.Treeable;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.service.sys.dto.AppConfigDto;
import com.pactera.jep.sys.model.AppConfig;
import com.pactera.jep.sys.service.AppConfigService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.TreeNode;
import com.pactera.jep.web.util.RequestUtils;
import com.pactera.jep.web.util.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "系统参数配置")
@RestController
@RequestMapping("/appConfig")
public class AppConfigRestController extends BaseRestController<AppConfig> {

	Logger logger = LoggerFactory.getLogger(AppConfigRestController.class);

	@Autowired
	AppConfigService appConfigService;

//	@Autowired
//	private JobEntityClient jobEntityClient;

	// ============================系统级别配置============================
	/**
	 * 系统级别配置页面
	 *
	 * @return
	 */
	@AutoLog(value = "查询系统配置",logType = LogType.OPERATE,operateType = OperateType.QUERY)
	@ApiOperation(value = "查询系统配置")
	@GetMapping(value = "/sysList", produces = "application/json;charset=UTF-8")
	public Map<String, Object> sysList(HttpServletRequest request) {
		Map<String, Object> tips = new HashMap<String, Object>();

        List<Filter> filters = RequestUtils.buildFilters(request);
		List<AppConfig> appConfigList = appConfigService.select(filters);
		for (AppConfig appConfig : appConfigList) {
			tips.put(appConfig.getConfigCode(), appConfig.getConfigValue());
			tips.put("DEFAULT_VALUE_", appConfig.getDefaultValue());
		}
		return tips;
	}

    /**
	 * 保存
	 *
	 * @param configs
	 * @return
	 */
	@ApiOperation(value = "保存一条数据")
	@PostMapping(value = "/save")
	public Map<String, Object> save(@RequestBody String configs) {
		Map<String, Object> tips = new HashMap<String, Object>();
		List<AppConfig> list = new ArrayList<>();

        JSONArray cfgs = (JSONArray) JSON.parse(configs);
		for (int i = cfgs.size() - 1; i >= 0; i--) {
			JSONObject cfg = cfgs.getJSONObject(i);
            AppConfig config = new AppConfig();
			config.setConfigCode(cfg.getString("name"));
			config.setConfigValue(cfg.getString("value"));
			config.setDefaultValue(cfg.getString("defaultValue"));
			list.add(config);
		}

		appConfigService.update(list);
		tips.put(WebCode.SUCCESS, true);
		tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		return tips;
	}

	// ============================应用级别配置============================

	/**
	 * 获取当前用户能访问的菜单
	 *
	 * @return
	 */
	@ApiOperation(value = "加载数据")
	@GetMapping("/load")
	public List<AppConfigDto> load() {
		List<AppConfigDto> appConfigDtos = new ArrayList<>();

		List<AppConfig> appConfigs = appConfigService.select(new Filter.Builder().eq("configLevel", "APP").build());
		for (AppConfig appConfig : appConfigs) {
			AppConfigDto appConfigDto = new AppConfigDto();

			appConfigDto.setId(appConfig.getConfigCode());
			appConfigDto.setTitle(appConfig.getConfigName());
			if (StringUtils.isNotBlank(appConfig.getParentId())) {
				String parentName = appConfigService.get(appConfig.getParentId()).getConfigName();
				appConfigDto.setParentName(parentName);
			}
			appConfigDto.setParentId(appConfig.getParentId());
			appConfigDto.setConfigCode(appConfig.getConfigCode());
			appConfigDto.setConfigName(appConfig.getConfigName());
			appConfigDto.setConfigDesc(appConfig.getConfigDesc());
			appConfigDto.setConfigValue(appConfig.getConfigValue());

			appConfigDtos.add(appConfigDto);
		}
		return generateAppConfigDto(null, appConfigDtos);
	}

	private List<AppConfigDto> generateAppConfigDto(AppConfigDto parent, List<AppConfigDto> appConfigDtos) {

		List<AppConfigDto> data = new ArrayList<>();

		for (AppConfigDto appConfigDto : appConfigDtos) {
			if (parent != null && parent.getId().equals(appConfigDto.getParentId())) {
				appConfigDto.setChildren(generateAppConfigDto(appConfigDto, appConfigDtos));
				data.add(appConfigDto);
			} else if (parent == null && StringUtils.isBlank(appConfigDto.getParentId())) {
				appConfigDto.setChildren(generateAppConfigDto(appConfigDto, appConfigDtos));
				data.add(appConfigDto);
			}
		}
		return data;
	}

	@ApiOperation(value = "根据id删除一条数据")
	@PostMapping(value = "/removeNode/{id}")
	public Map<String, Object> removeNode(@PathVariable String id) {
		Map<String, Object> tips = new HashMap<String, Object>();
		long count = appConfigService.count(new Filter.Builder().eq("parentId", id).build());
		if (count > 0) {
			tips.put("success", false);
			tips.put("msg", "请先删除子节点。");
		} else {
			this.appConfigService.deleteByPrimaryKey(id);
			tips.put("success", true);
			tips.put("msg", "删除成功。");
		}
		return tips;
	}

	@ApiOperation(value = "根据id修改节点name")
	@PostMapping(value = "/renameNode/{id}")
	public Map<String, Object> renameNode(@PathVariable String configCode, String newName) {
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			AppConfig appConfig = new AppConfig();
			appConfig.setConfigCode(configCode);
			appConfig.setConfigName(newName);
			appConfigService.update(appConfig, new String[] { "configName" });
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, "重命名成功。");
		} catch (Exception ex) {
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, "重命名失败。");
		}
		return tips;
	}

	@ApiOperation(value = "修改系统参数")
	@PostMapping(value = "/updateNode")
	public Map<String, Object> updateNode(@RequestBody AppConfig appConfig) {
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			AppConfig exist = appConfigService.get(appConfig.getConfigCode());
			appConfig.setConfigLevel("APP");
			if (exist == null) {
				appConfigService.insert(appConfig);
			} else {
				appConfigService.update(appConfig);
			}
			tips.put(WebCode.SUCCESS, true);
			tips.put(Treeable.TREE_ID, appConfig.getConfigCode());
			tips.put(WebCode.MSG, "保存成功");
		} catch (Exception ex) {
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, "保存失败");
		}
		return tips;
	}

	@ApiOperation(value = "获取树节点")
	@GetMapping(value = "/treeNode")
	public List<TreeNode> treeNode(String parentId, Model model, HttpServletRequest request) {
		List<Filter> filters = null;
		if (parentId == null) {
			filters = new Filter.Builder().nl("parentId").build();
		} else {
			filters = new Filter.Builder().eq("parentId", parentId).build();
		}
		filters.add(new Filter("configLevel", "APP"));
		List<AppConfig> list = appConfigService.select(filters);

		List<TreeNode> nodes = TreeUtils.parse(list, "parentId", "configCode", "configName", "inputType", "valueType",
				"configValue", "configDesc");
		return nodes;
	}

	@PostMapping("/getConfigValue")
	public String getConfigValue(String configCode){
		return appConfigService.getConfigValue(configCode);
	}

	@PostMapping("/get")
	public String get(String code) {
		AppConfig appConfig = appConfigService.get(code);
		if(appConfig != null){
			return JSONObject.toJSONString(appConfig);
		}
		return null;
	}

}
